using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.Approval;
using RBAC.Read.Api.Application.Dto.Approval;

namespace RBAC.Read.Api.Controllers
{
    /// <summary>
    /// 审批流程管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApprovalController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ApprovalController> logger;

        public ApprovalController(IMediator mediator, ILogger<ApprovalController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 测试接口连通性
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpGet]
        public IActionResult TestConnection()
        {
            try
            {
                logger.LogInformation("审批流程控制器测试接口被调用");
                return Ok(new
                {
                    success = true,
                    message = "审批流程控制器连接正常",
                    timestamp = DateTime.Now,
                    controller = "ApprovalController"
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "测试接口异常：{Message}", ex.Message);
                return StatusCode(500, new
                {
                    success = false,
                    message = "测试接口失败",
                    error = ex.Message,
                    timestamp = DateTime.Now
                });
            }
        }

        /// <summary>
        /// 获取审批流程列表
        /// </summary>
        /// <param name="request">查询参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>审批流程分页列表</returns>
        [HttpGet]
        public async Task<APIPaging<ApprovalProcessListDto>> GetApprovalProcessList(
            [FromQuery] GetApprovalProcessListCommand request,
            CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始获取审批流程列表，参数：{@Request}", request);
                var result = await mediator.Send(request, cancellationToken);
                logger.LogInformation("获取审批流程列表完成，返回{Count}条记录", result.PageDatas?.Count ?? 0);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取审批流程列表异常：{Message}", ex.Message);
                return new APIPaging<ApprovalProcessListDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"获取审批流程列表失败：{ex.Message}",
                    PageDatas = new List<ApprovalProcessListDto>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 根据流程类型获取审批流程列表（用于分组显示）
        /// </summary>
        /// <param name="processType">流程类型（采购订单/销售订单/入库单/出库单）</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>指定流程类型的审批流程列表</returns>
        [HttpGet]
        public async Task<APIResult<List<ApprovalProcessListDto>>> GetApprovalProcessByType(
            [FromQuery] string processType,
            CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始获取流程类型{ProcessType}的审批流程列表", processType);

                var command = new GetApprovalProcessListCommand
                {
                    ProcessType = processType,
                    PageIndex = 1,
                    PageSize = 1000, // 获取所有数据，不分页
                    OrderBy = "CreateTime DESC"
                };

                var result = await mediator.Send(command, cancellationToken);

                var apiResult = new APIResult<List<ApprovalProcessListDto>>
                {
                    Code = result.Code,
                    Msg = result.Msg,
                    Data = result.PageDatas ?? new List<ApprovalProcessListDto>()
                };

                logger.LogInformation("获取流程类型{ProcessType}的审批流程列表完成，返回{Count}条记录",
                    processType, apiResult.Data.Count);

                return apiResult;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取流程类型{ProcessType}的审批流程列表异常：{Message}", processType, ex.Message);
                return new APIResult<List<ApprovalProcessListDto>>
                {
                    Code = APIEnums.Error,
                    Msg = "获取审批流程列表失败",
                    Data = new List<ApprovalProcessListDto>()
                };
            }
        }

        /// <summary>
        /// 获取所有审批流程（按业务类型分组）
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>按业务类型分组的审批流程</returns>
        [HttpGet]
        public async Task<APIResult<Dictionary<string, List<ApprovalProcessListDto>>>> GetApprovalProcessGrouped(
            CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始获取分组审批流程列表");

                var command = new GetApprovalProcessListCommand
                {
                    PageIndex = 1,
                    PageSize = 1000, // 获取所有数据
                    OrderBy = "CreateTime DESC"
                };

                var result = await mediator.Send(command, cancellationToken);

                // 按流程类型分组
                var allProcesses = result.PageDatas ?? new List<ApprovalProcessListDto>();
                var groupedData = new Dictionary<string, List<ApprovalProcessListDto>>
                {
                    ["purchase"] = allProcesses.Where(x => x.ProcessType == "采购订单").ToList(),
                    ["sales"] = allProcesses.Where(x => x.ProcessType == "销售订单").ToList(),
                    ["inbound"] = allProcesses.Where(x => x.ProcessType == "入库单").ToList(),
                    ["outbound"] = allProcesses.Where(x => x.ProcessType == "出库单").ToList()
                };

                var apiResult = new APIResult<Dictionary<string, List<ApprovalProcessListDto>>>
                {
                    Code = result.Code,
                    Msg = result.Msg,
                    Data = groupedData
                };

                logger.LogInformation("获取分组审批流程列表完成，各组数据量：采购{Purchase}，销售{Sales}，入库{Inbound}，出库{Outbound}",
                    groupedData["purchase"].Count, groupedData["sales"].Count,
                    groupedData["inbound"].Count, groupedData["outbound"].Count);

                return apiResult;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取分组审批流程列表异常：{Message}", ex.Message);
                return new APIResult<Dictionary<string, List<ApprovalProcessListDto>>>
                {
                    Code = APIEnums.Error,
                    Msg = "获取审批流程列表失败",
                    Data = new Dictionary<string, List<ApprovalProcessListDto>>()
                };
            }
        }

        /// <summary>
        /// 按流程ID获取审批流程详情（包含节点列表）
        /// </summary>
        /// <param name="id">流程ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>流程详情DTO</returns>
        [HttpGet]
        public async Task<APIResult<ApprovalProcessDetailDto>> GetApprovalProcessDetail(
            [FromQuery] long id,
            CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("开始获取审批流程详情，Id={Id}", id);
                var cmd = new GetApprovalProcessDetailCommand { Id = id };
                var result = await mediator.Send(cmd, cancellationToken);
                logger.LogInformation("获取审批流程详情完成，返回Code={Code}", result.Code);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取审批流程详情异常：{Message}", ex.Message);
                return new APIResult<ApprovalProcessDetailDto>
                {
                    Code = APIEnums.Error,
                    Msg = "获取审批流程详情失败",
                    Data = null
                };
            }
        }
    }
}
